import axios from 'axios'
// import {  Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: process.env.baseUrl,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})
service.interceptors.request.use(
  config => {
    if ((config.method === 'post' || config.method === 'delete') && config.data && config.data.contentType) {
      config.headers = {
        'Content-Type': config.data.contentType
      }

      if (config.data.headerAccept) {
        config.headers = {
          'Content-Type': config.data.contentType,
          'Accept': config.data.headerAccept
        }
      }

      delete config.data.contentType
      delete config.data.headerAccept

      config.data = qs.stringify(config.data, {
        arrayFormat: 'brackets'
      })
    }
    if (config.method === 'get') {
      // get请求增加随机数
      if (!config.params) {
        config.params = {
          tt: new Date().getTime()
        }
      } else {
        config.params = Object.assign(config.params, {
          tt: new Date().getTime()
        })
      }
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (+res.errCode !== 0) {
      // Message({
      //   message: res.errMsg || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('==err' + error) // for debug
    // MessageBox.confirm('系统异常，请重新登陆', 'Confirm logout', {
    //   confirmButtonText: '重新登录',
    //   cancelButtonText: '取消',
    //   type: 'warning'
    // }).then(() => {
    //   store.dispatch('user/resetToken').then(() => {
    //     location.reload()
    //   })
    // })
    return Promise.reject(error)
  }
)

export default service
